<template>
  <ych-modal
    :fullscreen="false"
    :title="title"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    :cancelText="$t('m.common.button.close')">
    <a-form-item :label="$t('m.bpm.design.variable_expression')" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-input v-model="value" :placeholder="$t('m.bpm.design.variable_expression_placeholder')" allowClear></a-input>
    </a-form-item>

    <a-form-item :label="$t('m.bpm.design.variable_expression_available')" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-tag @click="appendSysbols('${userId()}')">{{$t('m.bpm.design.variable_expression_userId')}}：${userId()}</a-tag>
      <a-tag @click="appendSysbols('${userName()}')">{{$t('m.bpm.design.variable_expression_userName')}}：${userName()}</a-tag>
      <a-tag @click="appendSysbols('${deptId()}')">{{$t('m.bpm.design.variable_expression_deptId')}}：${deptId()}</a-tag>
      <a-tag @click="appendSysbols('${deptName()}')">{{$t('m.bpm.design.variable_expression_deptName')}}：${deptName()}</a-tag>
      <a-tag @click="appendSysbols('${deptShortName()}')">{{$t('m.bpm.design.variable_expression_deptShortName')}}：${deptShortName()}</a-tag>
      <a-tag @click="appendSysbols('${orgName()}')">{{$t('m.bpm.design.variable_expression_orgName')}}：${orgName()}</a-tag>
      <a-tag @click="appendSysbols('${getUserName(?)}')">{{$t('m.bpm.design.variable_expression_getUserName')}}：${getUserName(userId)}</a-tag>
      <a-tag @click="appendSysbols('${getDeptName(?)}')">{{$t('m.bpm.design.variable_expression_getDeptName')}}：${getDeptName(deptId)}</a-tag>
      <a-tag @click="appendSysbols('${getDeptShortName(?)}')">{{$t('m.bpm.design.variable_expression_getDeptShortName')}}：${getDeptShortName(deptId)}</a-tag>
      <a-tag @click="appendSysbols('${getOrgName(?)}')">{{$t('m.bpm.design.variable_expression_getOrgName')}}：${getOrgName(orgId)}</a-tag>
      <a-tag @click="appendSysbols('${formatDateStr(?,?)}')">{{$t('m.bpm.design.variable_expression_formatDateStr')}}：${formatDateStr(dateStr, "yyyy-MM-dd HH:mm:ss")}
      </a-tag>
    </a-form-item>

    <a-button-group style="margin-bottom: 8px;">
      <a-button icon="plus" @click="handleAdd" type="primary">{{$t('m.bpm.design.variable_add')}}</a-button>
    </a-button-group>
    <a-table
      size="small"
      bordered
      rowKey="id"
      :columns="columns"
      :pagination="false"
      :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
      :dataSource="data">

      <template slot="key" slot-scope="text, record">
        <ych-editable-cell v-if="visible && record.type != '1'" :text="text"
                           @change="onCellChange(record.id, 'key', $event)"/>
        <span v-else>
          {{ text }}
        </span>
      </template>
      <template slot="alias" slot-scope="text, record">
        <ych-editable-cell v-if="visible && record.type != '1'" :text="text"
                           @change="onCellChange(record.id, 'alias', $event)"/>
        <span v-else>
          {{ text }}
        </span>
      </template>

      <template slot="operation" slot-scope="text, record">
        <a @click="handleSelect(record)">{{$t('m.bpm.design.variable_select')}}</a>
        <template v-if="record.type != '1'">
          <a-divider type="vertical"/>
          <a @click="handleDel(record.id)">{{ $t('m.common.button.delete') }}</a>
        </template>
      </template>
    </a-table>

  </ych-modal>
</template>

<script>

import { getAction } from '@/api/manage'
import YchConstant from '@/api/YchConstant'
import {YchEditableCell} from '@yuncheng/ych-components'

export default {
  name: 'SelectVariable',
  components: {
    YchEditableCell
  },
  data() {
    return {
      title: this.$t('m.bpm.other.process_dialog'),
      visible: false,
      value: null,
      data: [],
      variables: [],
      formVariables: [],
      selectedRowKeys: [],
      formCode: null,
      labelCol: { xs: 24, sm: 6, lg: 4, xl: 2 },
      wrapperCol: { xs: 24, sm: 18, lg: 20, xl: 22 },
      columns: [{
        title:this.$t('m.common.label.number'),
        dataIndex: '',
        key: 'rowIndex',
        width: 50,
        align: 'center',
        customRender: function(t, r, index) {
          return parseInt(index) + 1
        }
      }, {
        title: this.$t('m.bpm.design.variable'),
        align: 'center',
        width: 180,
        dataIndex: 'key',
        scopedSlots: { customRender: 'key' }
      }, {
        title: this.$t('m.bpm.entity.varName'),
        align: 'center',
        width: 180,
        dataIndex: 'alias',
        scopedSlots: { customRender: 'alias' }
      }, {
        title: this.$t('m.bpm.design.variable_source'),
        align: 'center',
        width: 100,
        dataIndex: 'type',
        customRender: (text) => {
          if (text == '1') {
            return this.$t('m.bpm.design.variable_source_eform')
          } else {
            return this.$t('m.bpm.design.variable_srouce_custom')
          }
        }
      }, {
        title: this.$t('m.common.label.operate'),
        dataIndex: 'action',
        scopedSlots: { customRender: 'operation' },
        align: 'center',
        width: 120
      }],
      url: {
        getBpmFormVariableList: YchConstant.PREFIX_BPM + '/bpm-back/processDefRest/getBpmFormVariableList/v1'
      }
    }
  },
  methods: {
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
    },
    open(value, variables, formCode) {
      this.value = value

      this.variables = variables ? JSON.parse(variables) : []
      this.data = [...this.formVariables, ...this.variables]

      this.formCode = formCode

      this.visible = true
    },
    handleOk() {
      const variables = this.data.filter(item => item.type != '1' && item.key)
      this.$emit('selectFinished', this.value || null, JSON.stringify(variables))
      this.handleCancel()
    },
    handleCancel() {
      this.visible = false
    },
    onCellChange(key, dataIndex, value) {
      const data = [...this.data]
      const target = data.find(item => item.id === key)
      if (target) {
        target[dataIndex] = value
        this.data = data
      }
    },
    handleAdd() {
      const { data } = this
      const newData = {
        id: '' + Math.random(),
        key: '',
        alias: '',
        type: '2'
      }
      this.data = [...data, newData]
    },
    handleDel(id) {
      const data = [...this.data]
      this.data = data.filter(item => item.id !== id)
    },
    handleSelect(record) {
      if (record.key) {
        if (this.value && this.value.indexOf('?') > 0) {
          this.value = this.value.replace(/\?/g, record.key)
        } else {
          this.value = (this.value || '') + '${' + record.key + '}'
        }
      }
    },
    appendSysbols(sysbol) {
      if (sysbol == '${formatDateStr(?,?)}') {
        sysbol = '${formatDateStr(?,"yyyy-MM-dd HH:mm:ss")}'
      }
      this.value = (this.value || '') + sysbol
    }
  },
  watch: {
    formCode: {
      handler(val) {
        if (val) {
          getAction(this.url.getBpmFormVariableList, { formCode: val }).then((res) => {
            if (res.success) {
              this.formVariables = res.result
              this.data = [...this.formVariables, ...this.variables]
            } else {
              this.messageUtil.warning(res.message)
            }
          }).finally(() => {
          })
        } else {
          this.formVariables = []
          this.data = [...this.formVariables, ...this.variables]
        }
      },
      immediate: true
    }
  }
}
</script>
